package com.seek.service.imp;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONObject;
import com.seek.cache.CacheUtil;
import com.seek.core.BaseServiceImpl;
import com.seek.dao.SysUserDao;
import com.seek.inter.interdto.InterDtoUser;
import com.seek.model.entity.TSysUser;
import com.seek.service.SysUserService;
import com.seek.util.BeanUtils;
import com.seek.util.CommonUtil;

@Repository("sysUserService")
public class SysUserServiceImpl extends BaseServiceImpl<TSysUser> implements SysUserService {

	@Autowired
	public void setDao(SysUserDao sysUserDao) {
		super.setDao(sysUserDao);
	}
	public SysUserDao getDao() {
		return (SysUserDao) super.getDao();
	}
	
	public boolean checkUserExists(Long companyId, String phoneNo, String excludeId) throws Exception{
		if (CommonUtil.isEmpty(phoneNo))
			return false;
		String sql = "select id from t_sys_user where company_id=? and phone_no=?";
		if (!CommonUtil.isEmpty(excludeId))
			sql += " and id<>"+excludeId;
		return this.getDao().findMapBySql(sql, new Object[]{companyId,phoneNo}).size()>0 ? true : false;
	}
	
	public TSysUser save(JSONObject reqJson) throws Exception{
		TSysUser en = new TSysUser();
	
		en.setId(reqJson.getLong("userId"));
		en.setCompanyId(reqJson.getLong("companyId"));
		en.setUserName(reqJson.getString("userName"));
		en.setLoginName(reqJson.getString("loginName"));
		if (en.getId() == null || en.getId()<1){
			en.setPassword(reqJson.getString("password"));
		}
		en.setRoleId(reqJson.getLong("roleId"));
		en.setPhoneNo(reqJson.getString("phoneNo"));
		en.setIsAuditor(reqJson.getInteger("isAuditor"));
		en.setIsOverduer(reqJson.getInteger("isOverduer"));
		en.setHidePhone(reqJson.getInteger("hidePhone"));
		en.setRemark(reqJson.getString("remark"));
		
		// 检测数据完整性
		if (CommonUtil.isEmpty(en.getUserName()) || CommonUtil.isEmpty(en.getLoginName()) || en.getRoleId()== null || en.getRoleId()<1 || CommonUtil.isEmpty(en.getPhoneNo())){
			throw new Exception("参数不完整，请检查");
		}
		if ((en.getId() == null || en.getId()<1) && CommonUtil.isEmpty(en.getPassword())){
			throw new Exception("参数不完整，请检查");
		}
		
		String token = reqJson.getString("token");
		InterDtoUser user = CacheUtil.getLoginCache(token);
		if (en.getId() == null || en.getId()<1){
			en.setIsUsed(1);
			en.setCreateTime(new Date());
			en.setCreateUserId(CommonUtil.getLongValue(user.getId()));
			en.setModifyUserId(CommonUtil.getLongValue(user.getId()));
		}
		en.setModifyTime(new Date());
		return this.save(en);
	}
	
	public TSysUser saveAgentUser(JSONObject reqJson) throws Exception{
		TSysUser en = new TSysUser();
	
		en.setId(reqJson.getLong("userId"));
		en.setCompanyId(reqJson.getLong("companyId"));
		en.setUserName(reqJson.getString("userName"));
		en.setLoginName(reqJson.getString("loginName"));
		if (en.getId() == null || en.getId()<1){
			en.setPassword(reqJson.getString("password"));
		}
		en.setRoleId(reqJson.getLong("roleId"));
		en.setPhoneNo(reqJson.getString("phoneNo"));
		en.setAgentId(reqJson.getLong("agentId"));
		en.setRemark(reqJson.getString("remark"));
		en.setHidePhone(1); // 代理商用户默认就是隐藏手机中间4位
		// 检测数据完整性
		if (CommonUtil.isEmpty(en.getUserName()) || CommonUtil.isEmpty(en.getLoginName()) || en.getRoleId()== null || en.getRoleId()<1 || CommonUtil.isEmpty(en.getPhoneNo()) || en.getAgentId()==null || en.getAgentId()<1){
			throw new Exception("参数不完整，请检查");
		}
		if ((en.getId() == null || en.getId()<1) && CommonUtil.isEmpty(en.getPassword())){
			throw new Exception("参数不完整，请检查");
		}
		
		String token = reqJson.getString("token");
		InterDtoUser user = CacheUtil.getLoginCache(token);
		if (en.getId() == null || en.getId()<1){
			en.setIsUsed(1);
			en.setCreateTime(new Date());
			en.setCreateUserId(CommonUtil.getLongValue(user.getId()));
			en.setModifyUserId(CommonUtil.getLongValue(user.getId()));
		}
		en.setModifyTime(new Date());
		return this.save(en);
	}
	
	// 重写保存方法 
	@SuppressWarnings({ "rawtypes"})
	public TSysUser save(TSysUser entity) throws Exception {
		entity.setUserName(entity.getUserName().trim());
		entity.setLoginName(entity.getLoginName().trim());
		
		// 检测相同登录帐号的用户是否已存在
		String sql = "select 1 from t_sys_user where company_id=? and (login_name=? or phone_no=?)";
		if (entity.getId() != null && entity.getId()>0)
			sql += " and id<>"+entity.getId();
		List rows = this.getDao().findMapBySql(sql, new Object[]{entity.getCompanyId(), entity.getLoginName(),entity.getPhoneNo()});
		if (rows != null && rows.size() > 0){
			throw new Exception("已存在该登录帐号或手机号");
		}
		
		// 如果是新增：
		if (entity.getId() == null || entity.getId() <= 0){
			return this.getDao().insert(entity);		
		}else{
			TSysUser old = this.getDao().get(entity.getId());
			// 如果原记录不存在或者已被删除，则提示
			if (old == null || old.getIsUsed() == 0){
				throw new Exception("您当前编辑的用户已被人删除，无法修改。");
			}
			BeanUtils.copyPropertiesExclude(entity, old, new String[]{"id","companyId","lastLoginTime","authedIp","authodMac","reqTime","reqIp","reqMac","createUserId","createTime","isUsed"});
			return this.getDao().update(old);
		}
	}
}